package jxtcpserver

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"time"
)

type PoolClient struct {
	pool map[string]*Client
	mu   sync.Mutex
}
type Pool struct {
	pool   map[uint32]*PoolClient
	locker sync.RWMutex
}

func (p *Pool) Set(mid uint32, id string, c *Client) {
	p.locker.Lock()
	defer p.locker.Unlock()
	pl, ok := p.pool[mid]
	if !ok {
		pl = new(PoolClient)
		pl.pool = make(map[string]*Client)
		p.pool[mid] = pl
	}
	nowc, ok := pl.pool[id]
	if ok {
		fmt.Print("出现重复链接")
		nowc.onClose(errors.New("重复设置链接"))
	}
	pl.pool[id] = c
}
func (p *Pool) Del(mid uint32, id string) {
	p.locker.Lock()
	defer p.locker.Unlock()
	pl, ok := p.pool[mid]
	if ok {
		delete(pl.pool, id)
	}
}
func (p *Pool) SendMessage(m *Message) error {
	pl, ok := p.pool[m.MachineId]
	if !ok {
		return fmt.Errorf("此客户端没有链接可用")
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()
	for {
		select {
		case <-ctx.Done():
			return fmt.Errorf("链接超时")
		default:
			for _, c := range pl.pool {
				err := c.SendMessage(m)
				if err == nil {
					return nil
				}
			}
		}
	}

}
